//
//  HomeCell.swift
//  WBDemo
//
//  Created by Meng on 17/2/14.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SDWebImage

class HomeCell: UITableViewCell {

    @IBOutlet weak var iconImageView: UIImageView!
    
    @IBOutlet weak var verifiedImageView: UIImageView!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var vipImageView: UIImageView!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var sourceLabel: UILabel!
    
    @IBOutlet weak var contentLabel: UILabel!
    
    @IBOutlet weak var pictureCollectionView: PictureView!
    
    @IBOutlet weak var bottomView: UIView!
    
    @IBOutlet weak var forwardLabel: UILabel!
    
    
    var viewModel: HomeViewModel? {
        didSet {
            if let urlStr = viewModel?.status?.user?.profile_image_url {
                let url = URL(string: urlStr)
                
                iconImageView.sd_setImage(with: url)
            }
            
            verifiedImageView.image = viewModel?.verified_image
            
            nameLabel.text = viewModel?.status?.user?.screen_name
            
            if let vipImage = viewModel?.mbrank_image {
                vipImageView.image = vipImage
                nameLabel.textColor = UIColor.orange
            } else {
                vipImageView.image = nil
                nameLabel.textColor = UIColor.black
            }
            
            timeLabel.text = viewModel?.created_time
            
            sourceLabel.text = viewModel?.source_text
            
            contentLabel.attributedText = XMGKeyboardPackage.createMutableAttrString(str: viewModel?.status?.text ?? "", font: contentLabel.font)
            
            if let forwardText = viewModel?.forward_text {
                forwardLabel.attributedText = XMGKeyboardPackage.createMutableAttrString(str: forwardText, font: forwardLabel.font)
                forwardLabel.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * 10
            }
            
            pictureCollectionView.viewModel = viewModel
            
        }
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        // 如果不设置contentLabel的最大宽度，会导致bottomView.frame.maxY有误差
        // 设置正文最大宽度
        contentLabel.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * 10
    }
    
    // MARK: - 外部控制方法
    func calculateRowHeight(viewModel: HomeViewModel) -> CGFloat {
        self.viewModel = viewModel
        layoutIfNeeded()
        return bottomView.frame.maxY
    }

}

